﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using WeiTap.Restful;
using BrnMall.Core;
using BrnMall.Services;
using Newtonsoft.Json;
using QIDong.WeApp.Models;
using Ship.DaDa;

namespace QIDong.WeApp.Controllers
{
    public class ShipController : WebApi
    {
        /// <summary>
        /// 达达配送状态变更回调
        /// </summary>
        /// <returns></returns>
        public string Notify()
        {
            string content = string.Empty;
            Trace.TraceInformation("Ship.Notify() 开始 ");
            try
            {
                content = GetJsonParam();
                Trace.TraceInformation(string.Format("Ship.Notify() 参数:{0}", content));

                DaDaCallbackModel model = JsonConvert.DeserializeObject<DaDaCallbackModel>(content);

                //签名校验
                if (model != null)
                {
                    var orderInfo = Orders.GetOrderByOSN(model.order_id);
                    if (orderInfo != null)
                    {
                        //订单状态(待接单＝1 待取货＝2 配送中＝3 已完成＝4 已取消＝5 已过期＝7 指派单=8 妥投异常之物品返回中=9 妥投异常之物品返回完成=10 创建达达运单失败=1000 可参考文末的状态说明）
                        switch (model.order_status)
                        {
                            case 2:
                                Ships.AcceptOrder(orderInfo);                  //配送中
                                break;
                            case 3:
                                Ships.WorkOrder(orderInfo, model.dm_name, model.dm_mobile);   //配送中
                                break;
                            case 4:
                                Ships.FinishOrder(orderInfo);                  //已完成
                                break;
                            case 5:
                                Ships.CacelOrder(orderInfo);                   //已取消
                                break;
                            case 7:
                                Ships.ExpireOrder(orderInfo);                  //已过期
                                break;
                        }
                    }
                    else
                        Trace.TraceError("订单不存在!");
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(string.Format("Ship.Notify() 处理失败,错误消息:{0},返回:{1}", ex.Message, content));
            }

            Trace.TraceInformation("Ship.Notify() 结束 ");
            Ships.Log(content);
            return content;
        }

        /// <summary>
        /// 计算运费，返回价格、距离
        /// </summary>
        /// <param name="oid"></param>
        /// <returns></returns>
        public object GetShipFee(int oid)
        {
            OrderInfo orderInfo = AdminOrders.GetOrderByOid(oid);
            if (orderInfo == null)
                throw new Exception("订单不存在");

            if (string.IsNullOrEmpty(orderInfo.Address))
                throw new Exception("订单地址不能为空");

            //获取达达配送价格
            var shipModel = Ships.GetShipFee(orderInfo);
            if (!Ships.IsSuccess(shipModel))
                throw new Exception(shipModel.Msg);

            var model = new
            {
                ShipDistance = shipModel.Result.Distance,
                ShipFee = shipModel.Result.Fee,
                ShipAddress = orderInfo.Address
            };
            return model;
        }

        /// <summary>
        /// 序列号参数
        /// </summary>
        /// <param name="order_id"></param>
        /// <returns></returns>
        string GetSerializeParam(string order_id)
        {
            var body = new { order_id = order_id };
            SortedDictionary<string, object> sortParam = new SortedDictionary<string, object>();
            sortParam.Add("source_id", "73753");
            sortParam.Add("v", "1.0");
            sortParam.Add("format", "json");
            sortParam.Add("app_key", "dadad179cf9c75d1d3b");
            sortParam.Add("body", Function.ToJson(body));      //业务参数
            sortParam.Add("timestamp", Function.GetTimestamp());

            sortParam.Add("signature", Function.GetSign(sortParam));    //签名
            return Function.ToJson(sortParam);
        }

        /// <summary>
        /// 参数,json格式
        /// </summary>
        /// <returns></returns>
        string GetJsonParam()
        {
            string content;
            HttpRequest req = HttpContext.Current.Request;
            byte[] bytes = new byte[req.InputStream.Length];
            using (var sr = req.InputStream)
            {
                sr.Seek(0, SeekOrigin.Begin);   //将流设置为起始位置
                int length = sr.Read(bytes, 0, bytes.Length);
                content = Encoding.UTF8.GetString(bytes, 0, length);
            }
            return content;
        }

        string GetHtml(string postUrl, string paramData)
        {
            string result = string.Empty;
            HttpWebRequest request = null;
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
                request = (HttpWebRequest)WebRequest.Create(postUrl);
                request.ContentType = "application/json;charset=UTF-8";
                request.Timeout = 20000;
                request.ServicePoint.ConnectionLimit = 100;
                request.ReadWriteTimeout = 30000;
                request.Method = "POST";
                using (Stream newStream = request.GetRequestStream())
                {
                    newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                }

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        result = sr.ReadToEnd();
                    }
                    response.Close();
                }
            }
            catch (Exception e) { return result = string.Empty; }
            finally
            {
                if (request != null)
                    request.Abort();
                GC.Collect();
            }
            return result;
        }


        #region 测试环境，触发回调接口
        /// <summary>
        /// 发送模板消息
        /// </summary>
        /// <param name="oid"></param>
        /// <returns></returns>
        public bool SendMessage(int oid)
        {
            Orders.SendDeliverSuccessMessage(oid);
            return true;
        }

        public string AutoShip(string order_id)
        {
            var orderInfo = Orders.GetOrderByOSN(order_id);
            if (orderInfo == null) return "订单号不存在";
            Ships.AutoShip(orderInfo, DateTime.Now.ToString());
            return "成功";
        }
        /// <summary>
        /// 模拟接单
        /// </summary>
        /// <param name="order_id"></param>
        /// <returns></returns>
        public string TestAccept(string order_id)
        {
            var url = "http://newopen.qa.imdada.cn/api/order/accept";
            return GetHtml(url, GetSerializeParam(order_id));
        }

        /// <summary>
        /// 模拟取货
        /// </summary>
        public string TestFetch(string order_id)
        {
            var url = "http://newopen.qa.imdada.cn/api/order/fetch";
            return GetHtml(url, GetSerializeParam(order_id));
        }
        /// <summary>
        /// 模拟完成
        /// </summary>
        public string TestFinish(string order_id)
        {
            var url = "http://newopen.qa.imdada.cn/api/order/finish";
            return GetHtml(url, GetSerializeParam(order_id));
        }

        /// <summary>
        /// 客户取消订单
        /// </summary>
        public string TestCacel(string order_id)
        {
            var url = "http://newopen.qa.imdada.cn/api/order/cancel";
            return GetHtml(url, GetSerializeParam(order_id));
        }
        /// <summary>
        /// 订单过期
        /// </summary>
        public string TestExpire(string order_id)
        {
            var url = "http://newopen.qa.imdada.cn/api/order/expire";
            return GetHtml(url, GetSerializeParam(order_id));
        }

        #endregion
    }
}